package com.kfh.ybracelet.location;


import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.widget.MySeekBar;

/**
 * 添加安全区域
 *
 * @author fc
 */
public class SafeAreaAddActivity extends BaseActivity implements LocationSource, AMapLocationListener, AMap.OnCameraChangeListener {

    private TextView tv_title;
    private MySeekBar mSeekBar;
    protected boolean isTouchSeeked = false;
    private Button btn;
    private String TAG = getClass().getSimpleName();
    //    private LatLng mLatLng = null;
    private AMap aMap;
    private MapView mapView;
    private AMapLocationClient mlocationClient;

    /**
     * 安全区域的半径
     */
    private int mRadius;
    private Dialog addSafeAreaDialog;
    private String id;
    private ImageView iv_back;
    private LatLng currentlatlng;//当前地图的中心点坐标

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.add_safe_area);
        id = getIntent().getStringExtra("id");
        //进出动画效果
        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);

        mRadius = 100;//默认设置为100

        mapView = (MapView) findViewById(R.id.gdmap);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        initMap();
        // 加载控件
        initView();

        setListener();

    }

    private void initMap() {
        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        //显示比例尺
        aMap.getUiSettings().setScaleControlsEnabled(true);
    }

    private void setListener() {

        btn.setOnClickListener(this);
        aMap.setOnCameraChangeListener(this);

        /**
         * 进度拖动条监听器
         */
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            // 通知进度已经被修改
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
//                Log.e("aaa", "onProgressChanged");
                if (isTouchSeeked) {
                    mRadius = progress * 10 + 100;
                    mSeekBar.showSeekDialog(progress * 10 + 100 + "m");// 动态展示当前进度

                    LogUtil.e("tag", "区域的半径==" + mRadius);

                    addMarker(currentlatlng);
                    addCircle(currentlatlng, mRadius);

                } else {
                    mSeekBar.hideSeekDialog();
                }
            }

            // 通知用户已经开始一个触摸拖动手势
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // showControlView(3600000);
                isTouchSeeked = true;

            }

            // 通知用户触摸手势已经结束
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
//                Log.e(TAG, "onStopTrackingTouch");
                isTouchSeeked = false;
                mSeekBar.hideSeekDialog();
                // showControlView(sDefaultTimeout);
            }
        });
    }

    private void initView() {

        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.add_safe_area));
        iv_back = (ImageView) findViewById(R.id.iv_back);

        iv_back.setOnClickListener(this);

        mSeekBar = (MySeekBar) findViewById(R.id.seek_progress);
        mSeekBar.setMax(90);// 最大值90 因为有个默认的100
        btn = (Button) findViewById(R.id.btn);

    }


    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mapView != null)
            mapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
        mApplication.cancelPendingRequests(getClass().getName());
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mapView != null)
            mapView.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null)
            mapView.onSaveInstanceState(outState);
    }

    /**
     * 创建围栏
     */
    private void createSafeArea(String id, String lat, String lng) {

        JSONObject j = new JSONObject();
        j.put("id", id);
        j.put("radius", mRadius + "");
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("latitude", lat);
        j.put("longitude", lng);
        j.put("areaName", et_area_name.getText().toString().trim());

        HttpUtil.setPostRequest("创建中..", this, Constant.WEB_ROOT + Constant.ADDAREA,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(et_area_name.getWindowToken(), 0);

                            if (addSafeAreaDialog != null && addSafeAreaDialog.isShowing())
                                addSafeAreaDialog.dismiss();

//                            org.json.JSONObject j = new org.json.JSONObject(str);
                            showToast("添加成功");
                            finish();

                        } catch (Exception e) {
                            e.printStackTrace();
//                            showToast("创建失败");
                        }

                    }
                }, null);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.iv_back://返回

                finish();
                break;

            case R.id.btn://添加安全围栏

                addSafeArea();

                break;

            case R.id.tv_create://创建安全围栏

                if (CommonUtils.isNull(et_area_name.getText().toString().trim())) {
                    showToast("请输入安全区域名称");
                    return;
                }

                getData();
                break;

            case R.id.tv_cancle://取消

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_area_name.getWindowToken(), 0);

                if (addSafeAreaDialog != null && addSafeAreaDialog.isShowing()) {
                    addSafeAreaDialog.dismiss();
                }
                break;
            default:
                break;
        }
    }

    /**
     * //     * 添加安全围栏
     */
    private EditText et_area_name;

    private void addSafeArea() {

        addSafeAreaDialog = new Dialog(this, R.style.no_title);

        addSafeAreaDialog.setCancelable(false);
        addSafeAreaDialog.setCanceledOnTouchOutside(false);
        addSafeAreaDialog.show();

        addSafeAreaDialog.setContentView(R.layout.dialog_add_safe_area);

        et_area_name = (EditText) addSafeAreaDialog.findViewById(R.id.et_area_name);
        TextView tv_create = (TextView) addSafeAreaDialog.findViewById(R.id.tv_create);
        TextView tv_cancle = (TextView) addSafeAreaDialog.findViewById(R.id.tv_cancle);

        et_area_name.post(new Runnable() {

            @Override
            public void run() {
                InputMethodManager im = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                im.showSoftInput(et_area_name, 0);
            }
        });

        tv_create.setOnClickListener(this);
        tv_cancle.setOnClickListener(this);

    }

    private void getData() {

        if (currentlatlng == null)
            return;

        double lat = currentlatlng.latitude;
        double lng = currentlatlng.longitude;
        if (!CommonUtils.isNull(id) && !CommonUtils.isNull(lat + "") && !CommonUtils.isNull(lng + "")) {
            createSafeArea(id, lat + "", lng + "");
        }

    }

    private AMapLocationClientOption mLocationOption;

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            mLocationOption.setInterval(6000 * 1000);
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    private OnLocationChangedListener mListener;

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
//                mLocationErrText.setVisibility(View.GONE);
//                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                LatLng latLng = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                addMarker(latLng);
                addCircle(latLng, mRadius);//安全围栏圈
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));//移动到location位置,并设置缩放比例
            }
//            else {
//                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
//                Log.e("AmapErr", errText);
//                mLocationErrText.setVisibility(View.VISIBLE);
//                mLocationErrText.setText(errText);
//            }
        }
    }


    //    private Marker mLocMarker;
    BitmapDescriptor des = null;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(20, 0, 0, 180);

    private void addMarker(LatLng latlng) {
        if (des == null) {
            Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
                    R.mipmap.thumb);
            des = BitmapDescriptorFactory.fromBitmap(bMap);
        }

        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        aMap.clear();
        aMap.addMarker(options);
    }

    @Override
    public void finish() {
        super.finish();
        //进出动画效果
        overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
    }

    /**
     * 地图移动的时候回调
     *
     * @param cameraPosition
     */
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        Log.d(TAG, "==== onCameraChange ====" + cameraPosition.target.latitude + "," + cameraPosition.target.longitude);

//        aMap.clear();
        currentlatlng = new LatLng(cameraPosition.target.latitude, cameraPosition.target.longitude);
        addMarker(currentlatlng);
        addCircle(currentlatlng, mRadius);
    }

    private void addCircle(LatLng latlng, double radius) {

        Log.e(TAG, "安全围栏的大小:" + radius);

        aMap.addCircle(new CircleOptions()
                .center(latlng)
                .strokeWidth(1f)
                .fillColor(FILL_COLOR)
                .strokeColor(STROKE_COLOR)
                .radius(radius));
    }

    /**
     * 地图移动完成后回调
     *
     * @param cameraPosition
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
//        Log.d(TAG, "==== CameraPosition ====" + cameraPosition.target.latitude + "," + cameraPosition.target.longitude);
    }
}